package com.example.travelexpensemanager;

import java.util.ArrayList;
import java.util.Arrays;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class AddMember extends Activity {

	EditText etTitle, etAddMember, input;
	Button btnFinish, btnAddMember, btnUpdate, btnDelete, btnSuggestMembers,
			btnAddDateTime;
	Spinner spnMemberList, spnSuggestMembers;
	ArrayAdapter<String> adapter, adpSuggestMembersAdapter;
	ArrayList<String> memberList, arrSuggestMembersAdapter;
	DatabaseOperations databaseOperations;
	/* For maintaining the list of columns */
	String[] columns;
	/* For maintaining the list of attributes for the columns */
	ArrayList<String> attributes = new ArrayList<String>();
	TextView editDetails;
	String memberToBeReplaced, titleToBeReplaced;
	AlertDialog alertDialog;
	static boolean firstTimeSelected;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_member);

		/* Setting it true so that listener is not called by default */
		firstTimeSelected = true;

		/* Creating an object of DatabaseOperations to access its functions */
		databaseOperations = new DatabaseOperations(this);

		/* Initialising the controls with their id's */
		etTitle = (EditText) findViewById(R.id.etTitle);
		etAddMember = (EditText) findViewById(R.id.etAddMember);
		btnAddMember = (Button) findViewById(R.id.btnAddMember);
		btnFinish = (Button) findViewById(R.id.btnFinish);
		btnUpdate = (Button) findViewById(R.id.btnUpdate);
		btnDelete = (Button) findViewById(R.id.btnDelete);
		editDetails = (TextView) findViewById(R.id.editDetails);
		btnSuggestMembers = (Button) findViewById(R.id.btnSuggestMembers);
		btnAddDateTime = (Button) findViewById(R.id.addDateTime);

		/*
		 * Every time this activity is loaded the arraylist should be
		 * Initialised
		 */
		memberList = new ArrayList<String>();

		/* Creating the adapter for the spinner */
		adapter = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.simple_spinner_item, memberList);

		/* Initialising the spinner object */
		spnMemberList = (Spinner) findViewById(R.id.spnMemberList);

		/*
		 * Assigning the adapter to a spinner so that spinner shows arraylist of
		 * strings
		 */
		spnMemberList.setAdapter(adapter);

		/* Have to keep the Update delete and spinner for member list invisible */
		makeInvisible();

		btnAddMember.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				/* Open the database */
				databaseOperations.openWriteableDatabase();

				/* Validation if both text boxes are empty */
				if (etTitle.getText().toString().equals("")
						&& etAddMember.getText().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Both fields cannot be empty", Toast.LENGTH_SHORT)
							.show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}
				/* Validation for title textbox */
				if (etTitle.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Title field cannot be empty", Toast.LENGTH_SHORT)
							.show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}
				/* Validation for Addmember textbox */
				if (etAddMember.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Member field cannot be empty", Toast.LENGTH_SHORT)
							.show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}

				/* preparing the set of columns */
				columns = new String[] {
						DatabaseOperations.getAmounttabletitle(),
						DatabaseOperations.getAmounttableamount() };

				/* Preparing the where statement */
				String whereStatement = DatabaseOperations
						.getAmounttabletitle()
						+ "="
						+ "\'"
						+ etTitle.getText().toString() + "\'";

				/* Check if the title already exists */
				if (databaseOperations.retrieve(
						DatabaseOperations.getAmounttable(), columns,
						whereStatement, null, null, null, null) != null) {
					Toast.makeText(getApplicationContext(),
							"Title Already Exists", Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}

				/* Checking if the member already exists */
				if (memberList.contains(etAddMember.getText().toString()
						.replaceAll("\\s+", " ").trim())) {
					Toast.makeText(getApplicationContext(),
							"Member already added", Toast.LENGTH_SHORT).show();
				} else {
					/* Adding to the arraylist */
					memberList.add(etAddMember.getText().toString()
							.replaceAll("\\s+", " ").trim());
					/* So adding a pop up */
					Toast.makeText(
							getApplicationContext(),
							etAddMember.getText().toString()
									.replaceAll("\\s+", " ").trim()
									+ " is added as a member",
							Toast.LENGTH_SHORT).show();
					/* Refreshing the Add member textbox */
					etAddMember.setText("");
					// etTitle.setEnabled(false);

					/* Function to make the controls visible */
					makeVisible(adapter);

				}

				/* Closing the database */
				databaseOperations.closeDatabase();
			}
		});

		btnFinish.setOnClickListener(new OnClickListener() {

			@SuppressLint("ShowToast")
			@Override
			public void onClick(View v) {

				/* Open the database */
				databaseOperations.openWriteableDatabase();

				/* Validation for title textbox */
				if (etTitle.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"Title field cannot be empty", Toast.LENGTH_SHORT)
							.show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}

				/* Validation for Addmember textbox */
				if (memberList.size() == 0
						&& etAddMember.getText().toString().equals("")) {
					Toast.makeText(getApplicationContext(),
							"You have not added any member to the account",
							Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;

				}

				/* preparing the set of columns */
				columns = new String[] {
						DatabaseOperations.getAmounttabletitle(),
						DatabaseOperations.getAmounttableamount(),
						DatabaseOperations.getAmounttabletotalmembers() };

				/* Preparing the where statement */
				String whereStatement = DatabaseOperations
						.getAmounttabletitle()
						+ "="
						+ "\'"
						+ etTitle.getText().toString() + "\'";

				/* Check if the title already exists */
				if (databaseOperations.retrieve(
						DatabaseOperations.getAmounttable(), columns,
						whereStatement, null, null, null, null) != null) {
					Toast.makeText(getApplicationContext(),
							"Title Already Exists", Toast.LENGTH_SHORT).show();
					/* Closing the database */
					databaseOperations.closeDatabase();
					return;
				}
				/*
				 * Case Where the last member is to be added but Add member is
				 * not used but finished is used
				 */
				/* But first if the member already added */
				if (memberList.contains(etAddMember.getText().toString()
						.replaceAll("\\s+", " ").trim())) {
					Toast.makeText(getApplicationContext(),
							"Member already added", Toast.LENGTH_SHORT).show();
					databaseOperations.closeDatabase();
				} else {
					/* Adding to the arraylist */
					if (!etAddMember.getText().toString().equals(""))
						memberList.add(etAddMember.getText().toString()
								.replaceAll("\\s+", " ").trim());

					/* Inserting into the AmountTable */
					/****************************************************/
					/* Creating the column list */
					columns = new String[] {
							DatabaseOperations.getAmounttabletitle(),
							DatabaseOperations.getAmounttableamount(),
							DatabaseOperations.getAmounttabletotalmembers() };

					/* For the attributes */
					/* For the Title column */
					attributes.add(etTitle.getText().toString()
							.replaceAll("\\s+", " ").trim());
					/* For the amount column */
					attributes.add(String.valueOf(0));
					/* For the size column */
					attributes.add(String.valueOf(memberList.size()));

					if (databaseOperations.insertIntoTable(
							DatabaseOperations.getAmounttable(), columns,
							attributes) != -1)
						Toast.makeText(getApplicationContext(), "Row Added",
								Toast.LENGTH_SHORT);
					else
						Toast.makeText(getApplicationContext(),
								"Row Not Added", Toast.LENGTH_SHORT);

					attributes = new ArrayList<String>();
					/*******************************************************/

					/* Inserting into the Member Table */
					/****************************************************/
					/* Creating the column list */
					columns = new String[] {
							DatabaseOperations.getMembertabletitle(),
							DatabaseOperations.getMembertablemember() };

					/* For the attributes */
					attributes.add(etTitle.getText().toString());

					for (String str : memberList) {
						attributes.add(str);
						if (databaseOperations.insertIntoTable(
								DatabaseOperations.getMembertable(), columns,
								attributes) != -1)
							Toast.makeText(getApplicationContext(),
									"Row Added", Toast.LENGTH_SHORT);
						else
							Toast.makeText(getApplicationContext(),
									"Row Not Added", Toast.LENGTH_SHORT);
						attributes.remove(attributes.size() - 1);
					}

					/* Refreshing the attribute list */
					attributes = new ArrayList<String>();
					/*******************************************************/

					/* Refreshing both the textboxes */
					etTitle.setText("");
					etAddMember.setText("");
					// etTitle.setEnabled(true);
					/* Refreshing the arraylist */
					memberList = new ArrayList<String>();
					/* refreshing the attribute list */
					attributes = new ArrayList<String>();
					/* So that it goes back to the front screen */
					/* Close the database */
					databaseOperations.closeDatabase();
					finish();
				}
			}
		});

		btnDelete.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				/* Getting the member selected */
				String item = spnMemberList.getSelectedItem().toString();
				/* Removing the member */
				memberList.remove(item);
				/* Assigning the new member list to the spinner */
				spnMemberList.setAdapter(adapter);
				/* Making the contorls invisible in case the size is 0 */
				if (memberList.size() == 0) {
					makeInvisible();
				}
			}
		});

		btnUpdate.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxUpdateMember("Rename the member", "Enter the name");
			}
		});

		btnSuggestMembers.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxSuggestMember("Add earlier added members", "");
			}
		});

		btnAddDateTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				showDialogBoxAddDateTime("Add Date and Time",
						"Do you want to add date and time with the account name");
			}
		});

	}

	/* Adding a date and time in account */
	private void showDialogBoxAddDateTime(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		dialogBuilder.setPositiveButton("Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						if (etTitle.getText().length() == 0) {
							etTitle.setText(Utils.getCurrentDate() + " "
									+ Utils.getCurrentTime());
						} else {
							titleToBeReplaced = etTitle.getText().toString()
									.replaceAll("\\s+", " ");
							titleToBeReplaced = titleToBeReplaced + " : "
									+ Utils.getCurrentDate() + " " + Utils.getCurrentTime();
							etTitle.setText(titleToBeReplaced);
						}
						/* Set cursor at the end */
						etTitle.setSelection(etTitle.getText().length());
					}
				});
		dialogBuilder.setNegativeButton("Don't Add",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	/* Dialog box for suggesting the members to the user */
	private void showDialogBoxSuggestMember(String title, String message) {
		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);
		dialogBuilder.setMessage(message);

		/* Creating the spinner for the dialog box */
		spnSuggestMembers = new Spinner(this);
		arrSuggestMembersAdapter = new ArrayList<String>(
				Arrays.asList("Select"));
		/* Opening the database */
		databaseOperations.openWriteableDatabase();
		/* Retrieving only distinct columns from member table */
		arrSuggestMembersAdapter.addAll(databaseOperations.retrieveAll(
				DatabaseOperations.getMembertable(),
				new String[] { DatabaseOperations.getMembertablemember() },
				null, null, DatabaseOperations.getMembertablemember(), null,
				null));
		/* Closing the database */
		databaseOperations.closeDatabase();
		adpSuggestMembersAdapter = new ArrayAdapter<String>(
				getApplicationContext(), android.R.layout.simple_spinner_item,
				arrSuggestMembersAdapter);
		spnSuggestMembers.setAdapter(adpSuggestMembersAdapter);
		/******************************************/

		/* Adding the spinner to the dialog box */
		dialogBuilder.setView(spnSuggestMembers);

		spnSuggestMembers
				.setOnItemSelectedListener(new OnItemSelectedListener() {

					@Override
					public void onItemSelected(AdapterView<?> arg0, View arg1,
							int arg2, long arg3) {

						/*
						 * For the first time it is not selected but the moment
						 * anything is selected it happens
						 */
						if (firstTimeSelected == false) {

							if (!spnSuggestMembers.getSelectedItem().toString()
									.equalsIgnoreCase("select")) {
								/* Checking if the member already exists */
								if (memberList.contains(spnSuggestMembers
										.getSelectedItem().toString())) {
									Toast.makeText(getApplicationContext(),
											"Member already added",
											Toast.LENGTH_SHORT).show();
								} else {
									/* Adding to the arraylist */
									memberList.add(spnSuggestMembers
											.getSelectedItem().toString());
									Toast.makeText(
											getApplicationContext(),
											spnSuggestMembers.getSelectedItem()
													.toString()
													+ " is added as a member",
											Toast.LENGTH_SHORT).show();
									/* Function to make the controls visible */
									makeVisible(adapter);
								}
								firstTimeSelected = true;
								alertDialog.dismiss();
							}
						} else
							firstTimeSelected = false;

					}

					@Override
					public void onNothingSelected(AdapterView<?> arg0) {
					}
				});

		alertDialog = dialogBuilder.create();
		alertDialog.show();

	}

	/* Dialog box for Updating a member in the spinner */
	private void showDialogBoxUpdateMember(String title, String message) {

		/* Storing the member in a string */
		memberToBeReplaced = spnMemberList.getSelectedItem().toString();

		/* Firstly we create an object of AlertDialog.Builder */
		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
		/* Now we initialise its contents */
		dialogBuilder.setTitle(title);

		input = new EditText(this);
		input.setSingleLine();
		input.setText(memberToBeReplaced);
		/* Function to put the cursor at the last */
		Utils.setCursorPosition(input);
		dialogBuilder.setView(input);

		/* Adding an event listener for changing text */
		input.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				Utils.validateTextLength(input);
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});

		dialogBuilder.setPositiveButton("Rename",
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						/* In case the name is to changed then he can do it */
						memberList.add(input.getText().toString()
								.replaceAll("\\s+", " ").trim());
						/* Showing a pop up for renaming */
						if (!input.getText().toString().replaceAll("\\s+", " ")
								.trim().equals(memberToBeReplaced)) {
							Toast.makeText(
									getApplicationContext(),
									memberToBeReplaced
											+ " was renamed to "
											+ input.getText().toString()
													.replaceAll("\\s+", " ")
													.trim(), Toast.LENGTH_SHORT)
									.show();
						} else {
							Toast.makeText(getApplicationContext(),
									"Same name was not renamed",
									Toast.LENGTH_SHORT).show();
						}
						memberList.remove(memberToBeReplaced);

						/* Creating the adapter for the spinner */
						adapter = new ArrayAdapter<String>(
								getApplicationContext(),
								android.R.layout.simple_spinner_item,
								memberList);

						/*
						 * Assigning the adapter to a spinner so that spinner
						 * shows arraylist of strings
						 */
						spnMemberList.setAdapter(adapter);
					}
				});

		dialogBuilder.setNegativeButton("Cancel",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						return;
					}
				});

		AlertDialog alertDialog = dialogBuilder.create();
		alertDialog.show();
	}

	public void displayArrayList(ArrayList<String> arr) {

		if (arr == null)
			Toast.makeText(getApplicationContext(), "Nothing in The database",
					Toast.LENGTH_SHORT).show();
		else {
			for (String str : arr) {
				Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT)
						.show();
			}
		}
	}

	/* To make the controls invisible */
	public void makeInvisible() {
		btnUpdate.setVisibility(View.GONE);
		btnDelete.setVisibility(View.GONE);
		spnMemberList.setVisibility(View.GONE);
		editDetails.setVisibility(View.GONE);
	}

	public void makeVisible(ArrayAdapter<String> adapter) {
		/*
		 * Have to make the Update delete and spinner for member list Visible
		 * the moment the size increases
		 */
		spnMemberList.setAdapter(adapter);
		btnUpdate.setVisibility(View.VISIBLE);
		btnDelete.setVisibility(View.VISIBLE);
		spnMemberList.setVisibility(View.VISIBLE);
		editDetails.setVisibility(View.VISIBLE);
	}

}
